package com.hm.base.auto.helper;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 下午4:54:00 2017年9月19日
 * @version 1.0
 * @describe
 */
@Slf4j
@Component
public class SpringBeanUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		if (SpringBeanUtil.applicationContext == null) {
			SpringBeanUtil.applicationContext = context;
		}
		log.info(
				"========ApplicationContext配置成功,在普通类可以通过调用SpringBeanUtil.getAppContext()获取applicationContext对象,applicationContext={}",
				SpringBeanUtil.applicationContext);
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public static Object getBean(String name) {
		return getApplicationContext().getBean(name);
	}

	public static <T> T getBean(Class<T> clazz) {
		return getApplicationContext().getBean(clazz);
	}

	public static <T> T getBean(String name, Class<T> clazz) {
		return getApplicationContext().getBean(name, clazz);
	}

	private static DefaultListableBeanFactory beanFactory() {
		return (DefaultListableBeanFactory) getApplicationContext().getAutowireCapableBeanFactory();
	}

	/**
	 * 注册bean
	 * @param beanClass
	 */
	public static void registerBean(Class<?> beanClass) {
		beanFactory().registerBeanDefinition(beanClass.getName(),
				BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition());
	}

	/**
	 * 获取注册bean
	 * @param beanClass
	 * @return
	 */
	public static Object getRegisterBean(Class<?> beanClass) {
		return beanFactory().getBean(beanClass);
	}

}
